/*
 * main.c
 * Copyright (C) Thomas Andersen 2011 <thomas.1.andersen@gmail.com>
 * 
 * main.c is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * main.c is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

#include <gtk/gtk.h>
#include "config.h"
#include "gettextmacro.h"
#include "invulgotrackerapp.h"



#define CHECKSTR "invulgotracker"

bool CheckUnique(char *cmdline)
{
    bool unique = TRUE;
    char *filename = new char[PATH_MAX+1];
    
    sprintf(filename, "%s%s.id",g_get_home_dir(),"/.InvulgoTracker/");
    
    FILE *idfile = fopen(filename, "r");
    if (idfile) {
        char *line = new char[PATH_MAX+1];
        if (fgets(line,PATH_MAX,idfile)) {
            sprintf(filename, "/proc/%d/cmdline",atoi(line));
            FILE *procfile = fopen(filename, "r");
            if (procfile) {
                if (fgets(line,PATH_MAX,procfile)) {
                    int qi = strlen(line) - strlen(CHECKSTR);
                    int len = strlen(CHECKSTR);
                    while(qi>=0) {
                        if (!memcmp(&line[qi], CHECKSTR, len)) {
                            unique = FALSE;
                            break;
                        }
                        qi--;
                    }
                }
                fclose(procfile);
            }
        }
        fclose(idfile);
        delete[] line;
    }

    if (unique) {
        sprintf(filename, "%s%s.id",g_get_home_dir(),"/.InvulgoTracker/");
        
        FILE *idfile = fopen(filename, "w");
        if (idfile) {
            char line[21];
            sprintf(line,"%d",getpid());
            fputs(line,idfile);
            fclose(idfile);
        }
    }
    
    delete[] filename;
    return unique;
}




int main (int argc, char *argv[])
{
    gtk_set_locale ();
    
#ifdef ENABLE_NLS
    bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    textdomain (GETTEXT_PACKAGE);
#endif

    if (!CheckUnique(argv[0])) {
        printf(_("InvulgoTracker is already running.\n"));
        return 0;
    }
    
    gtk_init (&argc, &argv);

    InvulgoTrackerApp app;

    app.Run();
    
    return 0;
}
